package the.guanzhong.express.interfaces.controller;

import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.github.binarywang.wxpay.bean.result.BaseWxPayResult;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.wisteria.framework.web.APIResult;
import org.wisteria.framework.web.QueryResult;
import the.guanzhong.express.interfaces.controller.req.*;
import the.guanzhong.express.interfaces.controller.resp.OrderAddResp;
import the.guanzhong.express.interfaces.controller.resp.OrderListResp;
import the.guanzhong.express.service.ExpressOrderService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

/**
 * 订单信息控制器
 */
@Api(tags = "Express")
@Slf4j
@RestController
@RequestMapping("/express/order")
public class ExpressOrderController {

    @Resource
    private ExpressOrderService expressOrderService;

    /**
     * 新增订单
     * @param req
     * @return
     */
    @PostMapping("/add")
    public APIResult<OrderAddResp> add(@RequestBody @Valid OrderAddReq req) {
        return APIResult.success(expressOrderService.save(req));
    }

    /**
     * 修改订单状态
     * @param req   订单信息
     * @return
     */
    @PostMapping("/status/modify")
    public APIResult<Boolean> modifyOrderStatus(@RequestBody @Valid OrderStatusModifyReq req) {
        return APIResult.success(expressOrderService.modifyOrderStatus(req));
    }

    /**
     * 查询订单列表
     * @param req   查询条件
     * @return
     */
    @PostMapping("/list")
    public APIResult<List<OrderListResp>> list(@RequestBody @Valid OrderListReq req) {
        return APIResult.success(expressOrderService.list(req));
    }

    /**
     * 取消订单
     * @param req   订单信息
     * @return
     */
    @PostMapping("/cancel")
    public APIResult<Boolean> cancel(@RequestBody @Valid OrderCancelReq req) {
        return APIResult.success(expressOrderService.cancel(req));
    }

    /**
     * 订单支付
     * @param request   请求数据
     * @return
     */
    @PostMapping("/pay")
    public APIResult<Boolean> pay(HttpServletRequest request) {
        BufferedReader br;
        try {
            br = request.getReader();
            String str;
            StringBuilder wholeParams = new StringBuilder();
            while((str = br.readLine()) != null){
                wholeParams.append(str);
            }
            log.info("接收支付回调请求/pay:" + wholeParams);

            WxPayOrderNotifyResult result = BaseWxPayResult.fromXML(wholeParams.toString(), WxPayOrderNotifyResult.class);
            if (WxPayConstants.ResultCode.SUCCESS.equals(result.getReturnCode())
                    && WxPayConstants.ResultCode.SUCCESS.equals(result.getResultCode())) {
                OrderCompletePaymentReq req = new OrderCompletePaymentReq();
                req.setOrderId(Integer.parseInt(result.getOutTradeNo()));
                req.setOutTransactionId(result.getTransactionId());
                expressOrderService.completePayment(req);
            }
        } catch (IOException e) {
            log.error("接收支付回调请求异常", e);
        }
        return APIResult.success(true);
    }

    /**
     * 订单支付完成
     * @param req   请求数据
     * @return
     */
    @PostMapping("/complete-payment")
    public APIResult<Boolean> completePayment(@RequestBody @Valid OrderCompletePaymentReq req) {
        return APIResult.success(expressOrderService.completePayment(req));
    }

    /**
     * 获取订单信息
     * @param orderId   订单ID
     * @return
     */
    @GetMapping("/get")
    public APIResult<OrderListResp> get(@RequestParam("orderId") Integer orderId) {
        return APIResult.success(expressOrderService.get(orderId));
    }

    /**
     * 订单分页查询
     * @param req   查询条件
     * @return
     */
    @GetMapping("/page")
    public APIResult<QueryResult<OrderListResp>> page(OrderPageReq req) {
        return APIResult.success(expressOrderService.page(req));
    }


}
